const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

let alert = function(msg) {
  wx.showToast({
    title: msg,
    icon: 'none',
    duration: 3000
  })
}

/**
  * 获取坐标
  */
let getCoordinate = function (successCallBack, errorCallBack) {
  wx.getLocation({
    type: 'gcj02',
    success(res) {
      const latitude = res.latitude
      const longitude = res.longitude
      const speed = res.speed
      const accuracy = res.accuracy

      if (successCallBack) {
        successCallBack(longitude, latitude);
      }
    }
  })
}

/**
  * 上传坐标
  */
let uploadCoordinate = function (reqUrl, params, successCallBack) {
  wx.getLocation({
    type: 'gcj02',
    success(res) {
      const latitude = res.latitude
      const longitude = res.longitude
      const speed = res.speed
      const accuracy = res.accuracy

      params.lon = longitude
      params.lat = latitude

      wx.request({
        url: reqUrl,
        data: params,
        success: function (res) {
          console.log(res.data);
          if (res.data.code !== 1000) {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 3000
            })
            return;
          }

          successCallBack(res.data);
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST'
      })
    }
  })
}

module.exports = {
  formatTime: formatTime,
  alert: alert,
  getCoordinate: getCoordinate,
  uploadCoordinate: uploadCoordinate
}
